import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import viteSvgIcons from 'vite-plugin-svg-icons'
import { resolve } from 'path'
import commonjs from '@rollup/plugin-commonjs'
import externalGlobals from "rollup-plugin-external-globals"
import { createStyleImportPlugin, VxeTableResolve } from 'vite-plugin-style-import'
/**
 * * 扩展setup插件，支持在script标签中使用name属性
 * * usage: <script setup name="MyComp"></script>
 */
import vueSetupExtend from 'vite-plugin-vue-setup-extend'

/**
 * 生成开发环境代理配置信息
 *
 * @param {Array} val 代理配置数组
 *  格式示例：[['/api', 'http://127.0.0.1:8088'], ['/api', 'http://127.0.0.1:8088']]
 * @returns {Object} 代理配置对象
 */
export function createProxy(val = '') {
  let list = []
  if (val && (typeof val  == 'string' || val instanceof String)) {
    list = JSON.parse(val.replace(/'/g, '"'))
  } else {
    list = val
  }
  const rst = {}
  for (const [prefix, target] of list) {
    const isHttps = /^https:\/\//.test(target)
    rst[prefix] = {
      target: target,
      changeOrigin: true,
      // 代理websockets
      ws: true,
      // 重写的请求路径
      rewrite: (path) => path.replace(new RegExp(`^${prefix}`), ''),
      // 是否要验证SSL证书
      ...(isHttps ? { secure: false } : {}),
    }
  }
  return rst
}

const apiConfig = [['/api', 'http://192.168.0.155:8088/']]
// const apiConfig = [['/api', 'http://192.168.1.29:8088/']]

// https://vitejs.dev/config/
export default defineConfig({
  base: '',
  // 开发服务器选项
  server: {
    // 是否监听所有地址
    host: true,
    // 配置端口号
    port: 3000,
    // 为开发服务器配置自定义代理规则
    proxy: createProxy(apiConfig)
  },
  plugins: [
    vue(),
    vueSetupExtend(),
    //添加jsx/tsx支持
    vueJsx({}),

    /* 开启externalGlobals后，
       报错：TypeError: Cannot read properties of null (reading 'nodeType')，不知何故？？ */
    // externalGlobals({
    //   vue: "Vue",
    //   'element-plus': 'ElementPlus',
    // }),
    // svg
    viteSvgIcons({
      // Specify the icon folder to be cached
      iconDirs: [resolve(process.cwd(),'src/icons/svg')],
      // Specify symbolId format
      symbolId: 'icon-[dir]-[name]',
    }),

    // 按需引入vxe-table
    createStyleImportPlugin({
      resolves: [
        VxeTableResolve()
      ],
    })
  ],

  resolve: {
    alias: {
      "@": resolve(__dirname, 'src'), // 路径别名
      '@designer': resolve(__dirname, 'src/components/form-designer'), // 路径别名
    },
    extensions: ['.js', '.vue', '.json', '.ts'] // 使用路径别名时想要省略的后缀名，可以自己 增减
  },

  optimizeDeps: {
    include: ['@/../lib/vuedraggable/dist/vuedraggable.umd.js', 'quill']
  },

  css: {
    preprocessorOptions: {
      scss: {
        /* 自动引入全局scss文件 */
        additionalData: '@import "./src/styles/global.scss";'
      }
    }
  },

  build: {
    //minify: false,
    commonjsOptions: {
      exclude: [
        'lib/vuedraggable/dist/vuedraggable.umd.js,',  //引号前的逗号不能删，不知何故？？
        //'vue/dist/*.js'
      ],
      include: []
      //requireReturnsDefault: true
    },
    rollupOptions: {
      // 指定生产打包入口文件为index.htm
      input: {
        main: resolve(__dirname, 'index.html'),
      },

      // // 确保外部化处理那些你不想打包进库的依赖
      // external: ['vue', 'element-plus'],
      // output: {
      //   // 在 UMD 构建模式下为这些外部化的依赖提供一个全局变量
      //   globals: {
      //     vue: 'Vue', //报错：Failed to resolve module specifier "vue". Relative references must start with either
      //     'element-plus': 'ElementPlus',
      //   }
      // }
    }
  },

  define: {
    __VUE_PROD_HYDRATION_MISMATCH_DETAILS__: 'false'
  }
})
